package com.jushu.storbox.adapter;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jushu.storbox.R;
import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.actions.ThumbnailAction;
import com.jushu.storbox.callback.FileFolderInfoFileSizeSort;
import com.jushu.storbox.callback.FileFolderInfoNameSort;
import com.jushu.storbox.callback.FileFolderInfoTimeSort;
import com.jushu.storbox.callback.ICallback;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.constant.MessageCode;
import com.jushu.storbox.constant.UiConstant;
import com.jushu.storbox.database.DAOFactory;
import com.jushu.storbox.entities.ControlInfo;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.entities.FileType;
import com.jushu.storbox.handler.ClientExceptionRelateHandler;
import com.jushu.storbox.manager.DownloadTaskManager;
import com.jushu.storbox.operation.group.FileItemMoreOperation;
import com.jushu.storbox.service.ServiceFactory;
import com.jushu.storbox.task.tqueue.DownloadTask;
import com.jushu.storbox.util.DateUtil;
import com.jushu.storbox.util.DirectoryUtil;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PingYinUtil;
import com.jushu.storbox.util.PublicTools;
import com.jushu.storbox.view.dialog.PopupMenuWindow;
import com.jushu.storbox.view.resolve.extend.IFileList;
import com.jushu.storbox.view.viewImpl.PinProgressButton;
import com.huawei.sharedrive.sdk.android.exception.ClientException;

public class FileDisplayAdapter extends ListDisplayResolveAdapter<FileFolderInfo, FileItemMoreOperation<FileFolderInfo>> {

    public static final String TAG = FileDisplayAdapter.class.getSimpleName();
    private LayoutInflater mInflater;
    Context context;
    private PopupMenuWindow popWindow;

    private Map<FileFolderInfo, Boolean> selectMap = new HashMap<FileFolderInfo, Boolean>();

    public FileDisplayAdapter(Context context, List<FileFolderInfo> datasList) {
        super(datasList);
        mInflater = LayoutInflater.from(context);
        this.context = context;
    }

    @Override
    public void setMultiMode(boolean multiMode) {
        selectMap = new HashMap<FileFolderInfo, Boolean>();
        super.setMultiMode(multiMode);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder(mInflater, parent);
            convertView = holder.baseView;
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        FileFolderInfo data = getItem(position);
        holder.settitleContainerVisible(false);
        Comparator<FileFolderInfo> comparator = getComparator();
        if (comparator instanceof FileFolderInfoNameSort) {
            if (position == 0) {
                holder.settitleContainerVisible(true);
                holder.setTitleContent(PingYinUtil.convertFirstCharToString(data.getName()));
            } else if (position > 0) {
                FileFolderInfo lestData = getItem(position - 1);
                String lastIndex = PingYinUtil.convertFirstCharToString(lestData.getName());
                String thisIndex = PingYinUtil.convertFirstCharToString(data.getName());
                if (!thisIndex.equals(lastIndex)) {
                    holder.settitleContainerVisible(true);
                    holder.setTitleContent(thisIndex);
                }
            }
        } else if (comparator instanceof FileFolderInfoTimeSort) {
            if (position == 0) {
                holder.settitleContainerVisible(true);
                holder.setTitleContent(DateUtil.getDateFormatString(data.getModifiedAt(), DateUtil.MM_DD_YYYY_1));
            } else if (position > 0) {
                FileFolderInfo lestData = getItem(position - 1);
                String lastIndex = DateUtil.getDateFormatString(lestData.getModifiedAt(), DateUtil.MM_DD_YYYY_1);
                String thisIndex = DateUtil.getDateFormatString(data.getModifiedAt(), DateUtil.MM_DD_YYYY_1);
                if (!thisIndex.equals(lastIndex)) {
                    holder.settitleContainerVisible(true);
                    holder.setTitleContent(thisIndex);
                }
            }
        }

        holder.bindingData(position, data);

        return convertView;
    }

    @Override
    public void removeData(FileFolderInfo item) {
        super.removeData(item);
        selectMap.remove(item);
    }

    @Override
    public void cleanListDatasOnly() {
        super.cleanListDatasOnly();
    }

    public PopupMenuWindow getPopWindow() {
        return popWindow;
    }

    public void setPopWindow(PopupMenuWindow popWindow) {
        this.popWindow = popWindow;
    }

    public void selectAll() {
        for (FileFolderInfo item : objectList) {
            selectMap.put(item, true);
        }
        this.notifyDataSetChanged();
    }

    public void cancelSelectAll() {
        for (FileFolderInfo item : objectList) {
            selectMap.put(item, false);
        }
        this.notifyDataSetChanged();
    }

    public List<FileFolderInfo> getSelectedItems() {
        List<FileFolderInfo> result = new ArrayList<FileFolderInfo>();
        Iterator iterator = selectMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            if (Boolean.valueOf(entry.getValue().toString()).booleanValue()) {
                result.add((FileFolderInfo) entry.getKey());
            }
        }
        return result;
    }

    public class ViewHolder implements IViewHolder<FileFolderInfo> {
        // ui view
        View titleContainer;
        TextView titleContent;
        // content
        View baseView;
        ImageView mItemIcon;
        TextView mItemName;
        TextView mItemDate;
        TextView mItemSize;
        View layout_checkbox;
        CheckBox mItemCheckBox;
        View mItemMore;
        // when the item have to updata
        ImageView mItemUpdataIcon;
        // when download item
        View itemProcView;
        PinProgressButton itemProgress;
        // when the item sync success
        View itemFinishView;

        long thumbnailLastModifyAt;
        File thumbnail = null;
        Bitmap tempThumbnail = null;

        // data index
        int mIndex;
        // data
        FileFolderInfo mInfo;

        public FileFolderInfo getmInfo() {
            return mInfo;
        }

        public ViewHolder(LayoutInflater mInflater, ViewGroup parent) {

            // init view
            baseView = mInflater.inflate(R.layout.new_item_filelist, parent, false);
            titleContainer = baseView.findViewById(R.id.title_container);
            titleContent = (TextView) baseView.findViewById(R.id.title_content);
            mItemIcon = (ImageView) baseView.findViewById(R.id.item_type_img);
            mItemName = (TextView) baseView.findViewById(R.id.item_name_text);
            mItemDate = (TextView) baseView.findViewById(R.id.item_date_text);
            mItemSize = (TextView) baseView.findViewById(R.id.item_filelist_file_size);
            layout_checkbox = baseView.findViewById(R.id.layout_checkbox);
            mItemCheckBox = (CheckBox) baseView.findViewById(R.id.chx_file_item);
            mItemMore = baseView.findViewById(R.id.item_more_ll);

            // sync status view
            mItemUpdataIcon = (ImageView) baseView.findViewById(R.id.item_filestateupdate_img);
            // sync not finish
            itemProcView = baseView.findViewById(R.id.item_pin_progress_proc_icon);
            itemProgress = (PinProgressButton) baseView.findViewById(R.id.item_pin_progress);
            itemProgress.setMax(100);
            // sync finish
            itemFinishView = baseView.findViewById(R.id.item_pin_progress_finish_icon);

            // show more operation window
            mItemMore.setOnClickListener(new OnClickListener() {
                public void onClick(View view) {
                    int[] loction = new int[2];
                    view.getLocationOnScreen(loction);
                    int showMoreMenuY = loction[1];
                    if (popWindow != null) {
                        popWindow.showAtLocation(baseView, Gravity.TOP, 0, showMoreMenuY + (view.getHeight() / 2 + 20));
                    }
                    FileItemMoreOperation<FileFolderInfo> currentOperation = getOperation();
                    if (currentOperation != null) {
                        currentOperation.onItemMore(mIndex, mInfo);
                    }
                }
            });

            mItemCheckBox.setOnClickListener(new OnClickListener() {
                public void onClick(View arg0) {
                    if (selectMap.size() < 1) {
                        for (FileFolderInfo item : objectList) {
                            selectMap.put(item, false);
                        }
                    }
                    if (selectMap.get(mInfo) == null || !selectMap.get(mInfo)) {
                        selectMap.put(mInfo, true);
                        Iterator iterator = selectMap.entrySet().iterator();
                        while (iterator.hasNext()) {
                            Map.Entry entry = (Map.Entry) iterator.next();
                            if (!Boolean.valueOf(entry.getValue().toString()).booleanValue()) {
                                return;
                            }
                        }
                        ((IFileList) context).updateSelectAll(true);
                    } else {
                        selectMap.put(mInfo, false);
                        ((IFileList) context).updateSelectAll(false);
                    }
                }
            });
        }

        public void bindingData(int index, FileFolderInfo info) {
            mIndex = index;
            reBindingData(info);
            // bindding data
            mItemIcon.setImageResource(getTypeImgeID());
            if (info.isSync()) {
                ViewHolderController control = (ViewHolderController) info.getControlInfo();
                if (control != null) {
                    if (info.getTransStatus() == Constant.DOWNLOAD_SUCCESS_UPDATE_DB) {
                        control.startCheckUpdata();
                    }
                    if (control.getDownloadTask() == null) {
                        control.setDownloadTask(DownloadTaskManager.getTask(info.getId()));
                    }
                }
            }
            updataExtendsView();
        }

        private void reBindingData(FileFolderInfo info) {
            ControlInfo control = null;
            if (mInfo != null) {
                control = mInfo.getControlInfo();
                if (control != null) {
                    mInfo.setControlInfo(null);
                }
            }
            control = info.getControlInfo();
            if (control == null) {
                control = new ViewHolderController();
            }
            ((ViewHolderController) control).setViewHolder(this);
            info.setControlInfo(control);
            mInfo = info;
        }

        private File getThumbnailFile() {
            String iconPath = DirectoryUtil.genThumbnailFileFullName(context, mInfo);
            return new File(iconPath);
        }

        @SuppressLint("SimpleDateFormat")
        private String formatDate() {
            SimpleDateFormat timeDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
            return timeDateFormat.format(mInfo.getModifiedAt());
        }

        private int getTypeImgeID() {
            // LogUtil.i(TAG, "getTypeImgeID...");
            int typeImgResId = R.mipmap.default_file_icon;
            if (mInfo.getIsFile() == FileType.File.value()) {
                if (PublicTools.isFileType(mInfo.getName(), Constant.WORD_TYPE)) {
                    typeImgResId = R.mipmap.doc;
                } else if (PublicTools.isFileType(mInfo.getName(), Constant.PPT_TYPE)) {
                    typeImgResId = R.mipmap.ppt;
                } else if (PublicTools.isFileType(mInfo.getName(), Constant.IMAGE_TYPE)) {
                    thumbnail = getThumbnailFile();
                    typeImgResId = R.mipmap.empty_pic;
                    try {
                        if (!thumbnail.exists()) {
                            new ThumbnailAction().downloadThumbnailIcon(context, mInfo.getOwnerBy(), mInfo.getId(), thumbnail.getAbsolutePath(), handler);
                        } else {
                            Message msg_download = new Message();
                            msg_download.what = MessageCode.REQUEST_THUMBNAIL_INLOCAL;
                            handler.sendMessage(msg_download);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        LogUtil.e(TAG, "[getTypeImgeID] fileType is image that show fail..." + e.getLocalizedMessage());
                    }
                } else if (PublicTools.isFileType(mInfo.getName(), Constant.RAR_TYPE)) {
                    typeImgResId = R.mipmap.rar;
                } else if (PublicTools.isFileType(mInfo.getName(), Constant.ZIP_TYPE)) {
                    typeImgResId = R.mipmap.rar;
                } else if (PublicTools.isFileType(mInfo.getName(), Constant.VIDEO_TYPE)) {
                    typeImgResId = R.mipmap.video;
                } else if (PublicTools.isFileType(mInfo.getName(), Constant.MUSIC_TYPE)) {
                    typeImgResId = R.mipmap.music;
                } else if (PublicTools.isFileType(mInfo.getName(), Constant.TXT_TYPE)) {
                    typeImgResId = R.mipmap.txt;
                } else if (PublicTools.isFileType(mInfo.getName(), Constant.PDF_TYPE)) {
                    typeImgResId = R.mipmap.pdf;
                } else if (PublicTools.isFileType(mInfo.getName(), Constant.EXCEL_TYPE)) {
                    typeImgResId = R.mipmap.excel;
                } else {
                    typeImgResId = R.mipmap.default_file_icon;
                }
            } else {
                typeImgResId = R.mipmap.folder_im;
            }
            return typeImgResId;
        }

        ClientExceptionRelateHandler handler = new ClientExceptionRelateHandler() {

            @Override
            public Context getContext() {
                return context;
            }

            public void handleMessage(final Message msg) {
                switch (msg.what) {
                    case UiConstant.ITEM_UPDATA_EXTENDS_VIEW:
                        updataExtendsView();
                        break;
                    case UiConstant.ITEM_SETITEM_SELECTED:
                        mItemCheckBox.setChecked(true);
                        break;
                    case UiConstant.ITEM_SETITEM_UNSELECTED:
                        mItemCheckBox.setChecked(false);
                        break;
                    case MessageCode.REQUEST_THUMBNAIL_INLOCAL:
                        new Thread(new Runnable() {
                            public void run() {
                                LogUtil.i(TAG, "thumb path: " + thumbnail.getAbsolutePath());
                                if (thumbnail.exists()) {
                                    thumbnailLastModifyAt = thumbnail.lastModified();
                                }
                                Bitmap bmp = BitmapFactory.decodeFile(thumbnail.getAbsolutePath());
                                ShareDriveApplication.getInstance().addCloudBitmaps(bmp);
                                Message message = new Message();
                                message.what = UiConstant.UPDATE_TYPE_ICON;
                                message.obj = bmp;
                                handler.sendMessage(message);
                            }
                        }).start();
                        break;

                    case UiConstant.UPDATE_TYPE_ICON:// refresh image ui
                        Bitmap bmp = (Bitmap) msg.obj;
                        if (null != bmp) {
                            mItemIcon.setImageBitmap(bmp);
                        } else {
                            LogUtil.e(TAG, "bitmap is null, show default img...");
                        }
                        if (tempThumbnail != null && !tempThumbnail.isRecycled()) {
                            tempThumbnail.recycle();
                            tempThumbnail = null;
                        }
                        tempThumbnail = bmp;
                        break;

                    default:
                        super.handleMessage(msg);
                }
            }
        };

        @Override
        public View getHolderView() {
            return baseView;
        }

        @Override
        public FileFolderInfo getHolderDate() {
            return mInfo;
        }

        @Override
        public void updataHolderView() {
            // bindding data
            handler.sendEmptyMessage(UiConstant.ITEM_UPDATA_EXTENDS_VIEW);
        }

        public void updataExtendsView() {

            if (thumbnail != null && thumbnail.exists()) {// proc new version
                // pic
                if (thumbnailLastModifyAt != thumbnail.lastModified()) {
                    mItemIcon.setImageResource(getTypeImgeID());
                    thumbnailLastModifyAt = thumbnail.lastModified();
                }
            }

            // bindding data
            mItemName.setText(mInfo.getName());
            if (mInfo.getIsFile() == FileType.File.value()) {
                mItemDate.setVisibility(View.VISIBLE);
                mItemDate.setText(formatDate());
                mItemSize.setVisibility(View.VISIBLE);
                mItemSize.setText(PublicTools.changeBKM(String.valueOf(mInfo.getSize())));
            } else {
                mItemDate.setVisibility(View.VISIBLE);
                mItemDate.setText(formatDate());
                mItemSize.setVisibility(View.INVISIBLE);
            }
            if (isMultiMode()) {
                layout_checkbox.setVisibility(View.VISIBLE);
                mItemCheckBox.setChecked(selectMap.get(mInfo) == null ? false : selectMap.get(mInfo));
            } else {
                layout_checkbox.setVisibility(View.GONE);
            }

            Log.i("test", "mInfo.getTransStatus() = " + mInfo.getTransStatus());

            if (mInfo.isSync()) {
                ViewHolderController control = (ViewHolderController) mInfo.getControlInfo();
                switch (mInfo.getTransStatus()) {
                    case Constant.DOWNLOAD_SUCCESS_UPDATE_DB:
                        switch (mInfo.getContentSyncState()) {
                            case Constant.SYNC_STATUS_TRUE:
                                itemProcView.setVisibility(View.GONE);
                                itemFinishView.setVisibility(View.VISIBLE);
                                mItemUpdataIcon.setVisibility(View.GONE);
                                break;
                            case Constant.SYNC_STATUS_FALSE:
                                itemProcView.setVisibility(View.GONE);
                                itemFinishView.setVisibility(View.VISIBLE);
                                mItemUpdataIcon.setVisibility(View.VISIBLE);
                                break;
                        }
                        break;
                    case Constant.DOWNLOAD_CONTENT_NOT_SYNCHRONIZATION:
                        itemProcView.setVisibility(View.GONE);
                        itemFinishView.setVisibility(View.VISIBLE);
                        mItemUpdataIcon.setVisibility(View.VISIBLE);
                        break;
                    case Constant.DOWNLOAD_ISRUNNING_UPDATE_DB:
                        itemProcView.setVisibility(View.VISIBLE);
                        itemProgress.setProgress(mInfo.getProgress());
                        itemProgress.setMax(100);
                        mItemUpdataIcon.setVisibility(View.GONE);
                        itemFinishView.setVisibility(View.GONE);
                        break;
                    case Constant.DOWNLOAD_STOP_UPDATE_DB:
                        break;
                    case Constant.DOWNLOAD_FAIL_UPDATE_DB:
                        itemProcView.setVisibility(View.VISIBLE);
                        mItemUpdataIcon.setVisibility(View.VISIBLE);
                        itemFinishView.setVisibility(View.GONE);
                        break;
                    case Constant.DOWNLOAD_ISWAITING_UPDATE_DB:
                        itemProcView.setVisibility(View.VISIBLE);
                        mItemUpdataIcon.setVisibility(View.GONE);
                        itemFinishView.setVisibility(View.GONE);
                        break;
                    case Constant.DOWNLOAD_CANCEL_UPDATE_DB:
                    case Constant.DOWNLOAD_NON_UPDATE_DB:
                        itemProcView.setVisibility(View.GONE);
                        mItemUpdataIcon.setVisibility(View.GONE);
                        break;
                    case Constant.DOWNLOAD_RES_NOEXIST_NORIGHT:
                        itemProcView.setVisibility(View.GONE);
                        itemFinishView.setVisibility(View.GONE);
                        mItemUpdataIcon.setVisibility(View.GONE);
                        mInfo.setTransStatus(Constant.DOWNLOAD_NON_UPDATE_DB);
                        Toast.makeText(context, R.string.error_noexist_noright, Toast.LENGTH_SHORT).show();
                        break;
                    case Constant.DOWNLOAD_RES_NOSPACE:
                        itemProcView.setVisibility(View.GONE);
                        itemFinishView.setVisibility(View.GONE);
                        mItemUpdataIcon.setVisibility(View.GONE);
                        mInfo.setTransStatus(Constant.DOWNLOAD_NON_UPDATE_DB);
                        break;
                    default:
                        itemProcView.setVisibility(View.VISIBLE);
                        itemFinishView.setVisibility(View.GONE);
                        mItemUpdataIcon.setVisibility(View.GONE);
                        itemProgress.setProgress(mInfo.getProgress());
                }

            } else {
                itemProcView.setVisibility(View.GONE);
                itemFinishView.setVisibility(View.GONE);
                mItemUpdataIcon.setVisibility(View.GONE);
            }

            final String path = DirectoryUtil.generateFileDownloadPath(context,
                    mInfo.getOwnerId(), mInfo.getId(),
                    mInfo.getName());
            File f = new File(path);
            if (f.exists()) {
                itemFinishView.setVisibility(View.VISIBLE);
            } else {
                itemFinishView.setVisibility(View.GONE);
            }


        }

        public void settitleContainerVisible(boolean showFlag) {
            if (showFlag) {
                titleContainer.setVisibility(View.VISIBLE);
            } else {
                titleContainer.setVisibility(View.GONE);
            }
        }

        public void setTitleContent(String content) {
            titleContent.setText(content);
        }
    }

    public class ViewHolderController extends ControlInfo {
        private IViewHolder<FileFolderInfo> viewHolder = null;
        private boolean needUpdata = false;
        private DownloadTask downloadTask = null;
        private ICallback callback = new ICallback() {
            public void onStart() {
                viewHolder.getHolderDate().setProgress(0);
                notifyChange();
            }

            public void onFailure(Throwable t, int statusCode) {
                // viewHolder.getHolderDate().setTransStatus(Constant.DOWNLOAD_FAIL_UPDATE_DB);
                // notifyChange();
            }

            public void onSuccess() {
                viewHolder.getHolderDate().setProgress(100);
                viewHolder.getHolderDate().setTransStatus(Constant.DOWNLOAD_SUCCESS_UPDATE_DB);
                notifyChange();
            }

            public void onProgress(int currentProgress, long currentSize, long currentProcSize) {
                viewHolder.getHolderDate().setTransStatus(Constant.DOWNLOAD_ISRUNNING_UPDATE_DB);
                viewHolder.getHolderDate().setProgress(currentProgress);
                notifyChange();
            }

            @Override
            public void onStop() {
                viewHolder.getHolderDate().setTransStatus(Constant.DOWNLOAD_STOP_UPDATE_DB);
                notifyChange();
            }

            @Override
            public void onCanceled() {
                viewHolder.getHolderDate().setTransStatus(Constant.DOWNLOAD_CANCEL_UPDATE_DB);
                notifyChange();
            }

            @Override
            public void onDettach() {
            }
        };
        private Runnable updataStateCheckTask = null;

        public IViewHolder<FileFolderInfo> getViewHolder() {
            return viewHolder;
        }

        public void setViewHolder(IViewHolder<FileFolderInfo> viewHolder) {
            this.viewHolder = viewHolder;
        }

        public void startCheckUpdata() {
            if (updataStateCheckTask == null && viewHolder != null) {
                updataStateCheckTask = new Runnable() {
                    public void run() {
                        try {
                            if (viewHolder.getHolderDate().getIsFile() == FileType.File.value()) {
                                needUpdata = ServiceFactory.getRemoteFileService().isFileUpdate(context, viewHolder.getHolderDate());
                            } else if (viewHolder.getHolderDate().getIsFile() == FileType.Folder.value()) {
                                needUpdata = ServiceFactory.getRemoteFolderService().isUpdate(context, viewHolder.getHolderDate());
                            }
                            if (needUpdata) {
                                notifyChange();
                            }
                        } catch (ClientException e) {
                            LogUtil.e(TAG, e.getMessage());
                        } catch (Exception e) {
                            LogUtil.e(TAG, e.getMessage());
                        }
                        updataStateCheckTask = null;
                    }
                };
                new Thread(updataStateCheckTask).start();
            } else {
                // is checkking now
            }
        }

        public boolean isNeedUpdata() {
            return needUpdata;
        }

        public void setNeedUpdata(boolean needUpdata) {
            this.needUpdata = needUpdata;
        }

        @Override
        public void notifyChange() {
            if (viewHolder != null) {
                viewHolder.updataHolderView();
            }
        }

        public DownloadTask getDownloadTask() {
            return downloadTask;
        }

        public void setDownloadTask(DownloadTask downloadTask) {
            this.downloadTask = downloadTask;
            if (downloadTask != null) {
                downloadTask.setCallback(callback);
            }
        }
    }

    @Override
    protected Comparator<FileFolderInfo> getDefaultComparator() {
        Comparator<FileFolderInfo> result = null;
        SharedPreferences preference = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
        Editor edit = preference.edit();
        int file_sort_current = preference.getInt(UiConstant.FILE_SORT_CURRENT, UiConstant.SORT_BY_NAME);
        switch (file_sort_current & 0x000F) {
            case UiConstant.SORT_BY_NAME: // 0X0001
                result = new FileFolderInfoNameSort(file_sort_current);
                break;
            case UiConstant.SORT_BY_SIZE: // 0X0002
                result = new FileFolderInfoFileSizeSort(file_sort_current);
                break;
            case UiConstant.SORT_BY_TIME: // 0X0003
                result = new FileFolderInfoTimeSort(file_sort_current);
                break;
        }
        System.out.println("file_sort_current:" + Integer.toHexString(file_sort_current) + " " + (file_sort_current & 0x0001));
        edit.putInt(UiConstant.FILE_SORT_CURRENT, file_sort_current);
        edit.commit();
        return result;
    }

}
